package com.zatech.cgnci.project.base.interceptor;

import com.zatech.cgnci.project.base.utils.VerifyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.servlet.WebMvcRegistrations;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.Set;
import java.util.TreeSet;

@Component
public class InterceptorConfig implements WebMvcConfigurer, WebMvcRegistrations {

    @Autowired(required = false)
    Set<InterceptorSupport> interceptorSupportSet;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        if (VerifyUtils.isNotEmpty(interceptorSupportSet)) {
            //sort(interceptorSupportSet);
            interceptorSupportSet.forEach(interceptorSupport -> {
                if (VerifyUtils.isNotEmpty(interceptorSupport.getExcludePathPatterns())){
                    registry.addInterceptor(interceptorSupport)
                            .excludePathPatterns(interceptorSupport.getExcludePathPatterns());
                }else if (VerifyUtils.isNotEmpty(interceptorSupport.getPathPatterns())){
                    registry.addInterceptor(interceptorSupport)
                            .addPathPatterns(interceptorSupport.getPathPatterns());
                }else {
                    registry.addInterceptor(interceptorSupport);
                }
            });
        }
    }

    @Override
    public RequestMappingHandlerMapping getRequestMappingHandlerMapping(){
        return new PrefixUrlMapping();
    }

//    private Set<InterceptorSupport> sort(Set<InterceptorSupport> interceptorSupportSet) {
//        return new TreeSet<InterceptorSupport>((t1, t2) -> {
//            int o1 = t1.getClass().getAnnotation(Order.class) == null ? Integer.MAX_VALUE : t1.getClass().getAnnotation(Order.class).value();
//            int o2 = t1.getClass().getAnnotation(Order.class) == null ? Integer.MAX_VALUE : t1.getClass().getAnnotation(Order.class).value();
//            return o2 - o1;
//        }) {{
//            addAll(interceptorSupportSet);
//        }};
//    }

}
